'use strict';

const Controller = require('egg').Controller;
const uuidv4 = require('uuid/v4');
const fs = require('fs')
const crypto = require('crypto');
class HomeController extends Controller {
  async index() {
    this.ctx.body = 'hi, egg';
  }
  async login() {
    const { db } = this.ctx.app;
    const user = this.ctx.request.body
    let res = {}
    console.log(user)
    let sqlResult = await db.all(`select * from school where userName=? and password=?`, [user.name, user.password])
    if (sqlResult.length > 0) {
      res.result = true;
      res.message = sqlResult
    } else {
      res.result = false;
      res.message = '用户名或密码有误!'
    }

    this.ctx.body = res
  }


  async getSchool() {
    var count = await this.ctx.app.db.all('select count (*) as count from school')
    let sql = 'select * from school  where 1=1  '
    let query = this.ctx.query
    let index = query.pageSize * (query.pageIndex - 1)
    if (query.searchKey) {
      sql += ` and name like '%${query.searchKey}%'`;
      count = await this.ctx.app.db.all(`select count (*) as count from school where name like '%${query.searchKey}%'`)
    }
    if (query.pageSize && query.pageIndex) {
      sql += ` order by id desc limit ${query.pageSize} offset ${index} `
    }
    var result = await this.ctx.app.db.all(sql)
    let res = {
      data: result,
      count
    }
    this.ctx.body = res
  }
  async editorSchool() {
    const { db } = this.ctx.app;
    const school = this.ctx.request.body
    let res = await db.run(`update school set name=$name,number=$number,userName=$userName, password=$password,contact=$contact,phone=$phone,fkj=$fkj,mjj=$mjj where id=$id;`, school);
    this.ctx.body = res
  }

  async setSchool() {
    const { db } = this.ctx.app;
    const school = this.ctx.request.body
    let res;
    let sqlResult = await db.all(`select * from school where number='${school.$number}'`)
    console.log(sqlResult, '返回值')
    if (sqlResult.length > 0) {
      res = false;
    } else {
      res = await db.run(`insert into school (name, number,userName, password,contact,phone,fkj,mjj)
     values ($name,$number,$userName,$password,$contact,$phone,$fkj,$mjj)`, school);
    }
    this.ctx.body = res
  }


  async delSchool() {
    const { db } = this.ctx.app;
    const id = this.ctx.request.query.id;
    const res = await db.run(`delete from school where id = ${id}`);
    this.ctx.body = res
  }
  async allSchool() {
    var sql = 'select name,number from school';
    let result = await this.ctx.app.db.all(sql);
    this.ctx.body = result
  }

  async uploadImg() {
    const ctx = this.ctx;
    const stream = await ctx.getFileStream();
    var fileName = await this.saveFile(stream)
    // let fileName=`${uuidv4()}.jpg` 
    // let url =__dirname+ `./../public/img/${fileName}`
    // var writeStream = fs.createWriteStream(url);
    // console.log('开始读取')
    // stream.pipe(writeStream)
    // console.log(fileName)
    ctx.body = fileName
  }

  saveFile(stream) {
    return new Promise((resolve, reject) => {
      var arry = []
      var hash = crypto.createHash('md5');
      stream.on('data', function (data) {
        arry.push(data)
        hash.update(data)
      })
      stream.on('end', function (err) {
        if (err) reject(err)
        var fileName = hash.digest('hex') + '.jpg'
        // const buffers = arry.map(part => util.isBuffer(part) ? part : Buffer.from(part))
        fs.writeFile(__dirname + `./../public/img/${fileName}`, Buffer.concat(arry))
        resolve(fileName)
      })
    })
  }
}

module.exports = HomeController;
